<template>
  <div class="left">
    <el-card class="login">
      <template #header>
        <div class="card-header">
          <span>登录</span>
        </div>
      </template>
      <el-form ref="loginFormRef" :model="loginForm" label-width="auto" label-position="right">
        <el-form-item label="IP" prop="ip">
          <el-input v-model="loginForm.ip" />
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input v-model="loginForm.port" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button @click="logout">注销</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="channel">
      <template #header>
        <div class="card-header">
          <span>通道列表</span>
        </div>
      </template>
      <el-form label-width="auto" label-position="right" v-show="channelVisibility">
        <el-form-item label="通道列表">
          <el-select v-model="selectedChannel">
            <el-option
              v-for="channel in channels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onStartPlayback">预览</el-button>
          <el-button @click="onStopPlayback">停止</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <div class="center">
    <div id="videoPlugin"></div>
  </div>

  <div class="right">
    <el-card class="log-card">
      <template #header>
        <div class="log-card__header">
          <span>日志</span>
        </div>
      </template>
      <el-input type="textarea" autosize v-model="log" readonly></el-input>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from "vue";

const log = ref("");
const loginFormRef = ref(null);
const loginForm = reactive({
  ip: "172.16.0.241",
  port: 80,
  username: "admin",
  password: "Aa123456",
});
const szDeviceIdentify = ref(null);
const channelVisibility = ref(false);
const channels = ref([]);
const selectedChannel = ref(null);

const showLog = (content) => {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  log.value += `${hours}:${minutes}:${seconds} - ${content}\n`;
};

const initPlugin = () => {
  WebVideoCtrl.I_InitPlugin({
    bWndFull: true, // 单窗口双击全屏
    iWndowType: 1, // 分屏类型，默认值为 1，表示单画面
    bDebugMode: true, // JS 调试模式
    cbInitPluginComplete: function () {
      WebVideoCtrl.I_InsertOBJECTPlugin("videoPlugin").then(
        () => {
          showLog("插件初始化成功！");

          WebVideoCtrl.I_CheckPluginVersion().then((bFlag) => {
            if (bFlag) {
              alert("检测到新的插件版本，双击开发包目录里的HCWebSDKPlugin.exe升级！");
            } else {
            }
          });
        },
        () => {
          alert(
            "插件初始化失败，请确认是否已安装插件；如果未安装，请双击开发包目录里的HCWebSDKPlugin.exe安装！"
          );
        }
      );
    },
  });
};

const login = () => {
  WebVideoCtrl.I_Login(loginForm.ip, 1, loginForm.port, loginForm.username, loginForm.password, {
    timeout: 3000,
    success: function (xmlDoc) {
      szDeviceIdentify.value = loginForm.ip + "_" + loginForm.port;

      showLog(`登录成功！设备标识：${szDeviceIdentify.value}`);

      setTimeout(() => {
        getChannelList();
      }, 1000);
    },
    error: function (error) {
      console.log("登录失败，原因：", error);
    },
  });
};

const getChannelList = () => {
  if (null == szDeviceIdentify.value) {
    return;
  }

  WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify.value, {
    success: function (xmlDoc) {
      const channelNodes = xmlDoc.getElementsByTagName("InputProxyChannelStatus");
      const tempChannels = [];

      showLog(`可用通道数：${channelNodes.length}`);

      for (let i = 0; i < channelNodes.length; i++) {
        const channelNode = channelNodes[i];
        const id = channelNode.getElementsByTagName("id")[0]?.textContent;
        const name =
          channelNode.getElementsByTagName("name")[0]?.textContent ||
          `IPCamera ${i < 9 ? "0" + (i + 1) : i + 1}`;
        const online = channelNode.getElementsByTagName("online")[0]?.textContent;

        if (online === "false") {
          continue; // 跳过不在线的通道
        }

        tempChannels.push({ id, name });
      }

      channels.value = tempChannels; // 更新 channels 列表

      channelVisibility.value = true;
    },
    error: function (error) {
      console.log("获取数字通道失败！原因：", error);
    },
  });
};

const logout = async () => {
  if (null == szDeviceIdentify.value) {
    return;
  }

  try {
    await WebVideoCtrl.I_Logout(szDeviceIdentify.value);

    showLog(`登出成功！设备标识：${szDeviceIdentify.value}`);

    szDeviceIdentify.value = null;

    channelVisibility.value = false;
  } catch (error) {
    console.log(`登出失败！原因：`, error);
  }
};

const onStartPlayback = () => {
  const oWndInfo = WebVideoCtrl.I_GetWindowStatus(0);

  if (null == szDeviceIdentify.value) {
    return;
  }

  const startPlayback = () => {
    WebVideoCtrl.I_StartRealPlay(szDeviceIdentify.value, {
      iStreamType: 1,
      iChannelID: selectedChannel.value,
      success: function () {
        showLog("开始预览...");
      },
      error: function (error) {
        console.log("预览失败，原因：", error);
      },
    });
  };

  if (oWndInfo != null) {
    WebVideoCtrl.I_Stop({
      success: function () {
        startPlayback();
      },
    });
  } else {
    startPlayback();
  }
};

const onStopPlayback = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus();

  if (oWndInfo != null) {
    WebVideoCtrl.I_Stop({
      success: function () {
        showLog("停止预览成功");
      },
      error: function (error) {},
    });
  }
};

const destroyPlugin = async () => {
  try {
    await WebVideoCtrl.I_DestroyPlugin();
    showLog("销毁插件成功！");
  } catch (error) {
    console.log(`销毁插件失败！`, error);
  }
};

onMounted(() => {
  initPlugin();
});

onBeforeUnmount(async () => {
  await logout();
  await destroyPlugin();
});
</script>

<style></style>
